package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"new_ginblog/internal/models"
	"new_ginblog/internal/repositories"
	"new_ginblog/internal/utils/errormsg"
	"strconv"
)

var (
	cateStatusCode int
)

// AddCategory 增加分类
func AddCategory(c *gin.Context) {
	var Category models.Category
	_ = c.ShouldBindJSON(&Category)
	cateStatusCode = repositories.CheckCategory(Category.Name)

	// 查找分类是否已经存在
	if cateStatusCode == errormsg.ERROR_CATEGORY_NAME_USED {
		c.JSON(http.StatusOK, gin.H{
			"code": cateStatusCode,
			"msg":  errormsg.GetErrorMsg(cateStatusCode),
		})
		return
	}

	cateStatusCode = repositories.AddCategory(&Category)
	if cateStatusCode == errormsg.ERROR {
		c.JSON(http.StatusOK, gin.H{
			"code": errormsg.ERROR,
			"msg":  errormsg.GetErrorMsg(errormsg.ERROR),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": cateStatusCode,
		"msg":  errormsg.GetErrorMsg(cateStatusCode),
		"data": Category,
	})
}

// GetCategoryList 获取分类列表
func GetCategoryList(c *gin.Context) {
	var CategoryList []models.Category
	var count int64
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1 // -1 表示不使用
	}
	if pageNum == 0 {
		pageNum = -1 // -1 表示不使用
	}
	CategoryList, cateStatusCode, count = repositories.GetCategoryList(pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"code":  cateStatusCode,
		"msg":   errormsg.GetErrorMsg(cateStatusCode),
		"data":  CategoryList,
		"count": count,
	})
}

// UpdateCategory 修改分类
func UpdateCategory(c *gin.Context) {
	var Category models.Category
	_ = c.ShouldBindJSON(&Category)
	id, _ := strconv.Atoi(c.Param("id"))
	cateStatusCode = repositories.UpdateCategory(id, &Category)

	c.JSON(http.StatusOK, gin.H{
		"code": cateStatusCode,
		"msg":  errormsg.GetErrorMsg(cateStatusCode),
	})
}

// DeleteCategory 删除分类
func DeleteCategory(c *gin.Context) {
	var Category models.Category
	_ = c.ShouldBindJSON(&Category)
	id, _ := strconv.Atoi(c.Param("id"))
	cateStatusCode = repositories.DeleteCategory(id)
	c.JSON(http.StatusOK, gin.H{
		"code": cateStatusCode,
		"msg":  errormsg.GetErrorMsg(cateStatusCode),
	})
}
